#include "stdafx.h"

#include "MatSingleColor.h"
#include "Renderer.h"

const char* MatSingleColor::mVertexShader =
	"uniform mat4 uMVPMatrix;\n"
	"attribute vec4 aPosition;\n"
	"attribute vec4 aColor;\n"
	"varying vec4 vColor;\n"
	"void main() {\n"
	"  gl_Position = uMVPMatrix * aPosition;\n"
	//"  gl_Position = aPosition;\n"
	//"  gl_Position = aPosition * uMVPMatrix;\n"
	"  vColor = aColor;\n"
	"}\n";

const char* MatSingleColor::mFragmentShader =
#ifdef _ANDROID
	"precision mediump float;\n"
#endif
	"varying vec4 vColor;\n"
	"void main() {\n"
	"  gl_FragColor = vColor;\n"
	//"  gl_FragColor = vec4(1.0,0,0,1.0);\n"
	"}\n";


void MatSingleColor::initialize_once(){
    mProgram = createProgram(mVertexShader, mFragmentShader);
    CHECKGL;
    if (mProgram == 0) {
    	LOGE("can't compile material");
        return;
    }
    maPositionHandle = glGetAttribLocation(mProgram, "aPosition");
    CHECKGL;
    if (maPositionHandle == -1) {
    	LOGE("Could not get attrib location for aPosition");
    }

    maColorHandle = glGetAttribLocation(mProgram, "aColor");
    CHECKGL;
    if (maPositionHandle == -1) {
    	LOGE("Could not get attrib location for aColor");
    }

    //*
    muMVPMatrixHandle = glGetUniformLocation(mProgram, "uMVPMatrix");
    CHECKGL;
    if (muMVPMatrixHandle == -1) {
    	LOGE("Could not get attrib location for uMVPMatrix");
    }//*/
}

void MatSingleColor::initialize_common(){
	use_program(mProgram);
}

void MatSingleColor::initialize_specific(const GLfloat* buffer){
	if (set_buffer(buffer)){
		glVertexAttribPointer(maPositionHandle, 3, GL_FLOAT, false,
				VERTICES_STRIDE, buffer);
		CHECKGL;
		glEnableVertexAttribArray(maPositionHandle);
		CHECKGL;
		buffer+=3;//*VERTICES_STRIDE/sizeof(GLfloat);
		glVertexAttribPointer(maColorHandle, 4, GL_FLOAT, false,
				VERTICES_STRIDE, buffer);
		CHECKGL;
		glEnableVertexAttribArray(maColorHandle);
		CHECKGL;
	}

	glUniformMatrix4fv(muMVPMatrixHandle, 1, false, Renderer::get_singleton()->get_mvp_matrix());
	CHECKGL;
}

void MatSingleColor::update(const float& time){

}

GLuint MatSingleColor::get_vertex_stride() const{
	return VERTICES_STRIDE;
}
